<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Result</title>
</head>

<body>
<?php

if (!isset($_POST['submit'])) {
    exit('permission denied!');
}
$id = $_POST['id'];
$new_vote_to = array();
$new_vote_to = $_POST['vote_to'];
?>

<?php
include('conn.php');

$user_query = mysql_query( "SELECT * FROM user" )
    or die ('Database user query failed!');

while ($user = mysql_fetch_row($user_query)) {
    $get_votes[$user[0]] = $user[4];
    if ($user[0] == $id) {
        $vote_to = $user[5];
    }
}

$vote_query = mysql_query( "SELECT * FROM `vote` WHERE `id` = $id" )
    or die ('Database vote query failed!');

$orig_vote_to = array();
while ($row = mysql_fetch_row($vote_query)) {
    array_push($orig_vote_to, $row[2]);
}

if (!empty($orig_vote_to)) {
    foreach ($orig_vote_to as $v) {
        // if no longer vote to $v
        if (empty($new_vote_to) || !in_array($v, $new_vote_to)) {
            $get_votes[$v]--;
            $get_voted=$get_votes[$v];
            mysql_query( "DELETE FROM `vote` WHERE `id` = $id AND `vote_to` = $v" )
                or die('DELETE FROM old failed');
            mysql_query( "UPDATE user SET `get_voted` = $get_voted WHERE `id` = $v" )
                or die('UPDATE get_voted(-) failed');
        }
    }
}

if (!empty($new_vote_to)) {
    foreach ($new_vote_to as $v) {
        if (empty($orig_vote_to) || !in_array($v, $orig_vote_to)) {
            $get_votes[$v]++;
            $get_voted=$get_votes[$v];
            mysql_query( "INSERT INTO `vote` (`i`, `id`, `vote_to`) VALUES (NULL, $id, $v)" )
                or die('INSERT INTO new failed');
            mysql_query( "UPDATE user SET `get_voted` = $get_voted WHERE `id` = $v" )
                or die('UPDATE get_voted(+) failed');
        }
    }
}

$vote_to = $vote_to - count($orig_vote_to) + count($new_vote_to);
mysql_query ( "UPDATE user SET `vote_to` = $vote_to WHERE `id` = $id" )
    or die('UPDATE failed');
?>

<?php
$user_query = mysql_query( "SELECT * FROM user" )
    or die ('Database user(updated) query failed!');
?>

<h2>投票已更新！</h2>
<p><a href="show.php">查看学生网站及投票结果</a></p>
<p><a href="index.html">返回登录页面</a></p>
</body>
